
//
//  ZMEmotiontools.swift
//  ZMWeiboSwift
//
//  Created by pg on 2017/8/1.
//  Copyright © 2017年 pg. All rights reserved.
//

import UIKit

let NumOfPage = 20

//最近使用表情  归档解档路径
let RecentEmotionArrayPath = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as NSString).appendingPathComponent("recentEmotionAttay.archive")


//读取plist文件中的数据
class ZMEmotiontools: NSObject {

    //单例全局访问点
    static let sharedTools: ZMEmotiontools = ZMEmotiontools()
    
    
    
    //创建imotionBundle对象
    lazy var emotionBundle: Bundle = {
       
        let path = Bundle.main.path(forResource: "Emoticons.bundle", ofType: nil)!
        //根据路径创建bundle
        let bundle = Bundle(path: path)!
        return bundle
    }()
    
    
    //  默认表情
     lazy var defaultEmoticonArray: [ZMEmotionModel] = {
        return self.loadEmotionPlistData(folderName: "default", fileName: "info.plist")
    }()
    
    //  emoji表情
     lazy var emojiEmoticonArray: [ZMEmotionModel] = {
        return self.loadEmotionPlistData(folderName: "emoji", fileName: "info.plist")
    }()
    
    //  浪小花表情
     lazy var lxhEmoticonArray: [ZMEmotionModel] = {
        return self.loadEmotionPlistData(folderName: "lxh", fileName: "info.plist")
    }()
    
    //  最近表情
     lazy var recentEmoticonArray: [ZMEmotionModel] = {
        if let array = self.loadLocalRecentEmotionData(){
            return array
        }
        let array = [ZMEmotionModel]()
        return array
    }()
   //给表情视图准备所有的视图
     lazy var allEmotionArray:[[[ZMEmotionModel]]] = {
       return [
            [self.recentEmoticonArray],
            self.sectionWith(emotionArray: self.defaultEmoticonArray),
            self.sectionWith(emotionArray: self.emojiEmoticonArray),
            self.sectionWith(emotionArray: self.lxhEmoticonArray)
        ]
        
    }()
    
    
    private func loadEmotionPlistData(folderName:String,fileName:String)->[ZMEmotionModel]{
        
        
        let subPath = folderName + "/" + fileName
        let path = self.emotionBundle.path(forResource: subPath, ofType: nil)!
        
        //根据路径加载plist数据
        let dicArray = NSArray(contentsOfFile: path)!
        let modelArray = NSArray.yy_modelArray(with: ZMEmotionModel.self, json: dicArray) as! [ZMEmotionModel]
        
        //  遍历表情数组判断是否是图片表情，如果是图片表情设置图片的路径（图片所在文件夹及图片）
        for model in modelArray {
            if model.type == "0" {
                //  图片表情
                let path = folderName + "/" + model.png!
                //  记录图片路径
                model.path = path
            }
        }
        
        
        return modelArray
        
    }
    
    //将每种表情数组拆分成对应的二维数组
    private func sectionWith(emotionArray:[ZMEmotionModel])->[[ZMEmotionModel]]{
        
        //根据表情个数计算显示的页数
        let pagecount = (emotionArray.count-1)/NumOfPage + 1
        var tempArray = [[ZMEmotionModel]]()
        //遍历页数,取每页对应的表情数据
        for pageindex in 0..<pagecount{
            //开始截取的索引
            let loc = pageindex * NumOfPage
            //截取的长度
            var len = NumOfPage
            if loc + len > emotionArray.count{
                //数据越界  截取最后剩余的个数
                len = emotionArray.count - loc
                
            }
            let range = NSMakeRange(loc, len)
            //截取指定范围内的表情数据
            let subArray = (emotionArray as NSArray).subarray(with: range) as! [ZMEmotionModel]
            
            tempArray.append(subArray)
            
        }
        return tempArray
    }
    
    //保存表情数据,将最近使用的表情数据归档保存到本地
    func saveRecentEmotionArray(emotion:ZMEmotionModel,callBack: ()->()){
        //判断最近表情之中是否已经存在要保存的表亲
        for (i,recentEmotion) in recentEmoticonArray.enumerated() {
            
            if emotion.type == "0" {
                //说明是图片表情,比较表情描述
                if recentEmotion.chs == emotion.chs{
                    //如果有,就将原来有的在数组中删除
                    recentEmoticonArray.remove(at: i)
                    break
                }
            }else{
                //说明是emoji表情,需要比较表情的code
                if recentEmotion.code == emotion.code {
                    
                    recentEmoticonArray.remove(at: i)
                    break
                }
            }
        }
        
        //将需要保存的表情添加到最近表情的最前面
        recentEmoticonArray.insert(emotion, at: 0)
        //如果最近表情超过20个,删除最后一个表情
        if recentEmoticonArray.count > 20{
            recentEmoticonArray.removeLast()
        }
        //修改最近表情数据源
        allEmotionArray[0][0] = recentEmoticonArray
        
        //归档最近表情
        let result  = NSKeyedArchiver.archiveRootObject(recentEmoticonArray, toFile: RecentEmotionArrayPath)
        
        if result {
            callBack()
        }
        
    }
    
    //MARK:- 加载本地最近表情数据
    private func loadLocalRecentEmotionData()->[ZMEmotionModel]?{
        let localArray = NSKeyedUnarchiver.unarchiveObject(withFile: RecentEmotionArrayPath) as? [ZMEmotionModel]
    
        return localArray
    }
    //MARK:- 根据表情描述查找表情模型
    func selectEmotionWith(chs:String)->ZMEmotionModel?{
        /// 只查找图片表情，默认表情和浪小花表情
        for model in defaultEmoticonArray {
            if model.chs == chs {
                return model
            }
        }
        
        for model in lxhEmoticonArray {
            if model.chs == chs {
                return model
            }
        }
        return nil
    }
    
    
}
